﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace blackhouse.WebNemo.Business.Groups {
    internal class RecordConverter<T> where T : GroupRecord, new() {

        #region Fields

        private Func<T> instance;
        private IGroup group;

        #endregion

        #region Constructors

        public RecordConverter() : this(null) { }

        public RecordConverter(IGroup assocToGroup) {
            this.group = assocToGroup;
            this.instance = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
        }

        #endregion

        #region Methods

        internal T[] ConvertAll(IGroupRecord[] records) {
            if (records == null || records.Length == 0) return new T[0];
            if (group == null) this.group = Factory.Instance().GetGroup(records.First().BelongsToGroupId);
            T[] tRecords = new T[records.Length];
            for (int xr = 0; xr < records.Length; xr++) {
                tRecords[xr] = instance();
                tRecords[xr].SetObject(this.group, records[xr]);
            }
            return tRecords;
        }

        internal T Convert(IGroupRecord record) {
            if (record == null) return null;
            if (group == null) this.group = Factory.Instance().GetGroup(record.BelongsToGroupId);
            T tRecord = instance();
            tRecord.SetObject(this.group, record);
            return tRecord;
        }

        #endregion

    }
}
